package com.youzi.tunnel.server.manager;

import com.alibaba.fastjson.JSONObject;
import com.youzi.tunnel.common.Config;
import com.youzi.tunnel.common.utils.SystemUtils;
import com.youzi.tunnel.server.entity.Client;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Stream;

@Slf4j
public class ClientManager {

    //客户端表在内存的映射<clientId:Client>
    private static final Map<String, Client> clientMap = new ConcurrentHashMap<>();

    static {
        String envPath = SystemUtils.getEnvPath();
        StringBuilder content = new StringBuilder();

        //首先读取当前执行jar文件同目录下的config_client.json, 失败则去类路径读取
        try (Stream<String> stream = Files.lines(Paths.get(envPath + "/config_client.json"), StandardCharsets.UTF_8)) {
            stream.forEach(content::append);
        } catch (IOException e) {
            log.info("读取当前执行jar文件同目录下的config_client.json出现异常, 将读取类路径resource/config_client.json!");
            InputStream is = ClientManager.class.getClassLoader().getResourceAsStream("config_client.json");
            try {
                BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
                String line;
                while ((line = br.readLine()) != null) {
                    content.append(line);
                }
            } catch (IOException unsupportedEncodingException) {
                log.error("读取必要必要配置异常, 系统退出!");
                System.exit(2);
            }
        }

        List<Client> clients = JSONObject.parseArray(content.toString(), Client.class);
        clients.forEach(e -> {
            clientMap.put(e.getId(), e);
        });

        //默认加上服务端在线
        Client client0 = new Client("server", "服务器", "00:00:00:00", " 127.0 .0 .1 ", true);
        clientMap.put(client0.getId(), client0);
    }

    public static boolean isClientOnline(String clientId) {
        if (clientId == null) {
            return false;
        }
        return clientMap.get(clientId).isOnline();
    }

    /**
     * 获取客户端
     *
     * @param
     */
    public static Client getClient(String clientId) {
        return clientId == null ? null : clientMap.get(clientId);
    }

    /**
     * 获取客户端
     *
     * @param
     */
    public static Collection<Client> getClients() {
        return clientMap.values();
    }

    /**
     * 更新客户端
     *
     * @param client
     */
    public static void updateClientMap(Client client) {
        clientMap.put(client.getId(), client);
    }

    /**
     * 删除客户端
     *
     * @param clientId
     */
    public static void removeClientMap(String clientId) {
        clientMap.remove(clientId);
    }

    /**
     * 更新客户端
     *
     * @param client
     */
    public static void updateClient(Client client) {
        clientMap.put(client.getId(), client);
    }

    /**
     * 移除客户端
     */
    public static void removeClient(String clientId) {
        clientMap.remove(clientId);
    }

}
